import os
import tempfile
import uuid
from datetime import datetime, time

import requests
import fitz  # PyMuPDF
import logging
from PIL import Image
from werkzeug.utils import secure_filename
from config import PDF_IMG_FOLDER, PNG_OUTPUT_FOLDER

logging.basicConfig(level=logging.WARNING)  # 修改为WARNING级别
logger = logging.getLogger(__name__)


def convert_pdf_to_png(file=None, fileUrl=None, outputType='file', whichOne=0):
    try:
        os.makedirs(PDF_IMG_FOLDER, exist_ok=True)
        if file is None and fileUrl is None:
            return {"code": 2, "msg": "必须提供file或fileUrl参数"}
            
        result = []
        pdf_path = None
        doc = None
        response = None
        try:
            if file:
                # 直接使用文件，不检查后缀
                pdf_path = file
                try:
                    doc = fitz.open(pdf_path)  # 尝试打开验证
                except:
                    return {"code": 2, "msg": "文件内容不是有效的PDF格式"}
            else:
                if not fileUrl or not isinstance(fileUrl, str):
                    return {"code": 2, "msg": "fileUrl参数必须为有效字符串"}
                
                # 下载文件（不检查URL后缀）
                try:
                    logger.info(f"开始下载文件: {fileUrl}")
                    response = requests.get(fileUrl)
                    response.raise_for_status()
                    
                    # 直接保存为临时PDF文件
                    random_name = f"temp_{uuid.uuid4().hex}.pdf"
                    temp_path = os.path.join(PDF_IMG_FOLDER, random_name)
                    
                    logger.info(f"保存下载内容到临时文件: {temp_path}")
                    with open(temp_path, 'wb') as f:
                        for chunk in response.iter_content(chunk_size=8192):
                            f.write(chunk)
                    
                    # 记录文件大小
                    file_size = os.path.getsize(temp_path)
                    logger.info(f"下载完成，文件大小: {file_size}字节")
                    
                    # 保存原始文件副本用于调试
                    debug_path = os.path.join(PDF_IMG_FOLDER, f"debug_{random_name}")
                    os.rename(temp_path, debug_path)
                    logger.info(f"已保存调试文件: {debug_path}")
                    
                    pdf_path = debug_path
                    
                    # 尝试打开验证是否为有效PDF
                    try:
                        logger.info("尝试打开PDF文件验证")
                        doc = fitz.open(pdf_path)
                        logger.info(f"成功打开PDF文件，共{doc.page_count}页")
                    except Exception as e:
                        logger.error(f"打开PDF文件失败: {str(e)}")
                        # 保存错误信息到文件
                        with open(os.path.join(PDF_IMG_FOLDER, "error_log.txt"), 'a') as f:
                            f.write(f"{datetime.now().isoformat()} - 文件URL: {fileUrl}\n")
                            f.write(f"错误信息: {str(e)}\n\n")
                        return {"code": 2, "msg": "下载内容不是有效的PDF文件"}
                        
                except requests.exceptions.RequestException as e:
                    logger.error(f"下载文件失败: {str(e)}")
                    return {"code": 2, "msg": f"无法下载文件: {str(e)}"}
            
            # 确保文件处理后正确关闭
            doc = fitz.open(pdf_path)
            images = []
            
            # 处理页码选择
            if whichOne == 0:
                pages = range(len(doc))
            else:
                if whichOne > len(doc):
                    return {"code": 2, "msg": f"请求的页码{whichOne}超出范围(1-{len(doc)})"}
                pages = [whichOne - 1]
            
            for page_num in pages:
                page = doc.load_page(page_num)
                pix = page.get_pixmap()
                img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
                images.append(img)
            
            if not images:
                return {"code": 2, "msg": "未生成任何图片"}
                
            os.makedirs(PNG_OUTPUT_FOLDER, exist_ok=True)
            
            for i, img in enumerate(images):
                output_path = os.path.join(PNG_OUTPUT_FOLDER, f"page_{i + 1}.png")
                img.save(output_path, 'PNG')
                
                if outputType == 'fileUrl':
                    from routes.pdf_png import upload_to_ftp  # 导入FTP上传函数
                    # 上传图片到FTP并获取URL
                    with open(output_path, 'rb') as f:
                        ftp_url = upload_to_ftp(f.read(), f"page_{i+1}.png")
                    result.append(ftp_url)
                else:
                    result.append(output_path)
            
            return {"code": 1, "msg": "", "data": result}
        finally:
            if doc:
                doc.close()
            if pdf_path and os.path.exists(pdf_path):
                try:
                    # 确保文件关闭后再删除
                    for _ in range(3):  # 重试3次
                        try:
                            os.remove(pdf_path)
                            break
                        except PermissionError:
                            time.sleep(0.5)
                except Exception as e:
                    logger.error(f"删除临时文件失败: {str(e)}")
            
            # 如果outputType是'file'，保留PNG文件供后续使用
            # 如果是'fileUrl'，PNG文件会在路由函数中被删除
    except Exception as e:
        logger.error(f"转换失败: {str(e)}")
        return {"code": 2, "msg": str(e)}
